package com.mouse.magent.proxy.action;

import com.mouse.magent.common.net.TcpClient;
import com.mouse.magent.common.protocol.Command;
import com.mouse.magent.common.protocol.Message;
import com.mouse.magent.common.service.BaseAction;
import com.mouse.magent.common.util.PropUtil;
import com.mouse.magent.common.util.StringUtil;
import com.mouse.magent.proxy.constant.ChannelConstant;
import com.mouse.magent.proxy.handler.ProxyLocalHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RemoteConnectAction extends BaseAction {
    private static String proxyIp;
    private static Integer proxyPort;

    @Override
    public void handle(ChannelHandlerContext ctx, Message message) throws Exception {
        try {
            TcpClient tcpClient = new TcpClient();
            tcpClient.connect(proxyIp, proxyPort, new ChannelInitializer() {
                @Override
                protected void initChannel(Channel channel) throws Exception {
                    ProxyLocalHandler proxyLocalHandler = new ProxyLocalHandler(ctx, message.getHeader().getChannelId());
                    channel.pipeline().addLast(new ByteArrayDecoder(),
                            new ByteArrayEncoder(), proxyLocalHandler);
//                    ChannelConstant.getChannelGroup().add(channel);
                    ChannelConstant.getChannelHandlerMap().put(message.getHeader().getChannelId(), proxyLocalHandler);
                }
            });
        } catch (Exception e) {
            message.setType(Command.REMOTE_DISCONNECT);
            ctx.writeAndFlush(message);
            ChannelConstant.getChannelHandlerMap().remove(message.getHeader().getChannelId());
            throw e;
        }
    }


    static {
        String tempProxyIp = PropUtil.getValue("proxy.ip", "127.0.0.1");
        if (StringUtil.isNotBlank(tempProxyIp)) proxyIp = tempProxyIp;

        Integer tempProxyPort = Integer.valueOf(PropUtil.getValue("proxy.port", "10004"));
        if (tempProxyPort != null) proxyPort = tempProxyPort;
    }
}
